package cn.mengfly.testnrz.netty.protobuf;

import cn.mengfly.testnrz.json.JsonUtil;
import cn.mengfly.testnrz.nio.NioDemoConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.string.StringDecoder;
import lombok.Data;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonServer {

    ServerBootstrap b = new ServerBootstrap();

    public void runServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // length(4) + content
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0,4,0,4));
                    ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                    ch.pipeline().addLast(new JsonMsgDecoder());
                }
            });
            ChannelFuture sync = b.bind(NioDemoConfig.SOCKET_PORT).sync();
            System.out.println("服务器启动成功，监听端口："+ sync.channel().localAddress());
            ChannelFuture closeFuture = sync.channel().closeFuture();
            closeFuture.sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    static class JsonMsgDecoder extends MessageToMessageDecoder<String> {

        @Override
        protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
            JsonMsg jsonMsg = JsonUtil.jsonToPojo(msg, JsonMsg.class);
            System.out.println("收到一个Json数据包 => " + jsonMsg);
            out.add(jsonMsg);
        }
    }

    @Data
    public static class JsonMsg {
        private Integer id;
        private String content;
    }

    public static void main(String[] args) {
        new JsonServer().runServer();
    }

}
